# -*- coding:utf-8 -*-
import json
from rest_framework import serializers
from .models import Contract, Task, DataStorage
from users.models import AuthUser, Registry, Person, CompanyAutoSubmit
from basic.models import ElevatorInfo
import datetime
import time


class MaintainSerializer(serializers.ModelSerializer):

    class Meta:
        model = Contract
        fields = ('id', 'contract_no', 'contract_type', 'maintain_company', 'property_company', 'start_time',
                  'end_time', 'sign_time', 'contract_name', 'maintain_cycle', 'contract_file', 'service_id')


class MaintainListSerializer(serializers.ModelSerializer):
    maintain_company_name = serializers.SerializerMethodField()
    property_company_name = serializers.SerializerMethodField()
    update_by_people = serializers.SerializerMethodField()
    contract_file = serializers.SerializerMethodField()
    elevator_info = serializers.SerializerMethodField()
    record = serializers.SerializerMethodField()
    contract_status = serializers.SerializerMethodField()

    class Meta:
        model = Contract
        # fields = MaintainSerializer.Meta.fields + ('register_code', 'elevator_property')
        fields = ('id', 'contract_no', 'contract_type', 'maintain_company', 'property_company', 'start_time',
                  'end_time', 'contract_name', 'maintain_cycle', 'maintain_company_name', 'property_company_name',
                  'update_by_people', 'update_time', 'sign_time', 'contract_file', 'elevator_info', 'record',
                  'registry_status', 'contract_status')

    def get_contract_status(self, obj):
        now_time = datetime.datetime.combine(datetime.date.today(), datetime.time())
        three_month_time = now_time + datetime.timedelta(days=90)
        contract_end_date = obj.end_time
        if u"/" in contract_end_date:
            contract_end_time_lis = contract_end_date.split("/")
            contract_end_time = "-".join(contract_end_time_lis)
            contract_end_time = datetime.datetime.strptime(contract_end_time, "%Y-%m-%d")
            print type(contract_end_time)
        else:
            contract_end_time = datetime.datetime.strptime(contract_end_date, "%Y-%m-%d")
        # if now_time > contract_end_time:
        if contract_end_time < now_time:
            contract_status = "#F56C6C"
            return contract_status
        elif now_time <= contract_end_time <= three_month_time:
            contract_status = "#E6A23C"
            return contract_status
        elif contract_end_time > three_month_time:
            contract_status = "#67C23A"
            return contract_status

    def get_maintain_company_name(self, obj):
        return obj.maintain_company.name if obj.maintain_company else None

    def get_property_company_name(self, obj):
        return obj.property_company.name if obj.property_company else None

    def get_elevator_info(self, obj):
        contact_id = obj.id
        elevator_info = list()
        try:
            elevator_qs = ElevatorInfo.objects.filter(contract=contact_id)
            for item in elevator_qs:
                elevator_msg = dict()
                elevator_msg['elevator'] = item.id
                elevator_msg['elevator_name'] = item.elevator_name
                elevator_msg['register_code'] = item.register_code
                elevator_info.append(elevator_msg)
        except:
            return None
        return elevator_info

    def get_contract_file(self, obj):
        if obj.contract_file:
            contract_file = json.loads(obj.contract_file)
            return contract_file
        else:
            return None

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None

    def get_record(self, obj):
        registry_obj = Registry.objects.filter(type_for_reg=obj.__class__.__name__, reg_obj_id=obj.id).\
            order_by('end_time').last()
        request = self.context.get("request", None)
        role = request.user.role
        record = {
            "start_time": u"",
            "end_time": u"",
            "status": u"",
            "msg": u"",
            "data": u"",
            "reg_info": u"",
            "ret_info": u""
        }
        if registry_obj:
            if role == 0 and registry_obj.reg_info:
                reg_info = json.loads(registry_obj.reg_info)
            else:
                reg_info = u""
            if role == 0 and registry_obj.ret_info:
                ret_info = json.loads(registry_obj.ret_info)
            else:
                ret_info = u""
            record.update({
                "rec_start_time": registry_obj.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                "rec_end_time": registry_obj.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                "rec_status": registry_obj.status,
                "msg": registry_obj.msg,
                "data": registry_obj.data,
                "reg_info": reg_info,
                "ret_info": ret_info
            })
        return record


class TaskSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ("id", "sn", "day", "worker", "status", "elevator", "result", "estate_confirm", "desc",
                  "maintain_type")


class TaskListSerializer(serializers.ModelSerializer):
    elevator_no = serializers.SerializerMethodField()
    internal_no = serializers.SerializerMethodField()
    # use_company_name = serializers.SerializerMethodField()
    maintain_company_name = serializers.SerializerMethodField()
    property_company_name = serializers.SerializerMethodField()
    update_by_name = serializers.SerializerMethodField()
    # worker_1_name = serializers.CharField(source='worker_1.auth_user.real_name')
    # worker_2_name = serializers.CharField(source='worker_2.auth_user.real_name')
    elevator_worker = serializers.SerializerMethodField()
    register_code = serializers.SerializerMethodField()
    elevator_cycle = serializers.SerializerMethodField()
    worker = serializers.SerializerMethodField()
    property_company_id = serializers.SerializerMethodField()
    record = serializers.SerializerMethodField()
    maintain_sign_image = serializers.SerializerMethodField()
    maintain_person_name = serializers.SerializerMethodField()
    elevator_type = serializers.SerializerMethodField()
    auto_submit = serializers.SerializerMethodField()
    persons = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = TaskSerializer.Meta.fields + ("elevator_no", "internal_no", "update_by", "update_by_name",
                                               "elevator_worker", "maintain_company_name", "worker", "register_code",
                                               "property_company_name", "elevator_cycle", "lng", "lat", "signature",
                                               "task_end_time", "property_company_id", "record", "maintain_sign_image",
                                               "maintain_person_name", "elevator_type", "auto_submit", "persons",
                                               "estate_confirm", "task_start_time")

    def get_auto_submit(self, obj):
        company = obj.elevator.maintain_company
        c = CompanyAutoSubmit.objects.filter_active(company=company).first()
        return c.auto_submit if c else True

    def get_maintain_person_name(self, obj):
        maintain_person_name = obj.maintainer_name
        return maintain_person_name

    def get_maintain_sign_image(self, obj):
        maintain_sign_image = obj.maintain_signature
        return maintain_sign_image

    def get_elevator_no(self, obj):
        return obj.elevator.elevator_no

    def get_elevator_cycle(self, obj):
        return obj.elevator.elevator_cycle

    def get_register_code(self, obj):
        register_code = obj.elevator.register_code
        return register_code

    def get_internal_no(self, obj):
        return obj.elevator.internal_no

    def get_maintain_company_name(self, obj):
        return obj.elevator.maintain_company.name

    def get_property_company_name(self, obj):
        return obj.elevator.property_company.name

    def get_property_company_id(self, obj):
        return obj.elevator.property_company.id

    def get_elevator_type(self, obj):
        return obj.elevator.get_elevator_type_display()

    def get_elevator_worker(self, obj):
        elevator_worker = []
        persons_ids = json.loads(obj.worker)
        for person_id in persons_ids:
            person_info = {}
            person_name = Person.objects.get(id=person_id).auth_user.real_name
            person_info['person_name'] = person_name
            person_info['person_id'] = person_id
            elevator_worker.append(person_info)
        return elevator_worker

    def get_worker(self, obj):
        worker = obj.worker
        worker = json.loads(worker)
        return worker

    def get_record(self, obj):
        registries = Registry.objects.filter(type_for_reg='Task', reg_obj_id=obj.id)
        record = []
        for r in registries:
            # start_time = str(r.start_time)
            # end_time = str(r.end_time)
            # status = r.status
            # msg = r.msg
            # data = r.data
            # if data:
            #     import ast
            #     data = ast.literal_eval(data)
            # reg_info = json.loads(r.reg_info)
            # ret_info = json.loads(r.ret_info)
            # task_type = r.get_task_type_display()
            # record.append({
            #     'start_time': start_time,
            #     'end_time': end_time,
            #     'status': status,
            #     'msg': msg,
            #     'data': data,
            #     'reg_info': reg_info,
            #     'ret_info': ret_info,
            #     'task_type': task_type
            #     })
            record.append(json.loads(r.reg_info))
            record.append(json.loads(r.ret_info))
        return record

    # def get_use_company_name(self, obj):
    #     contrat = obj.elevator.contract
    #     return obj.elevator.contract.use_company_name if contrat else None

    def get_update_by_name(self, obj):
        update_by = AuthUser.objects.filter(id=obj.update_by).first()
        return update_by.username if update_by else ""

    def get_persons(self, obj):
        persons = []
        persons_ids = json.loads(obj.worker)
        for person_id in persons_ids:
            person_info = {}
            authuser = Person.objects.get(id=person_id).auth_user
            person_info['person_name'] = authuser.real_name
            person_info['person_id'] = authuser.id
            persons.append(person_info)
        return persons


class AppTaskListSerializer(serializers.ModelSerializer):

    elevator_no = serializers.SerializerMethodField()
    elevator_name = serializers.SerializerMethodField()
    workers = serializers.SerializerMethodField()
    t_lng = serializers.SerializerMethodField()
    t_lat = serializers.SerializerMethodField()
    register_code = serializers.SerializerMethodField()
    use_company = serializers.SerializerMethodField()
    workers_all = serializers.SerializerMethodField()
    elevator_inner_no = serializers.SerializerMethodField()
    qr_code = serializers.SerializerMethodField()
    need_sign = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = ("id", "qr_code", "elevator_name", "elevator_no", "maintain_type", "day", "workers", "status", "sn",
                  "create_time", "task_end_time", "elevator", "result", "estate_confirm", "desc", "t_lng", "t_lat",
                  "register_code", "use_company", "workers_all", 'property_comfirm_time', 'elevator_inner_no',
                  "need_sign", "task_start_time")

    def get_need_sign(self, obj):
        if obj.status in (30, 50, 60, 70, 80, 90, 110, 120, 130, 140) and not obj.estate_confirm:
            return True
        return False

    def get_qr_code(self, obj):
        return obj.elevator.qr_code

    def get_elevator_inner_no(self, obj):
        return obj.elevator.internal_no

    def get_elevator_no(self, obj):
        return obj.elevator.elevator_no

    def get_elevator_name(self, obj):
        return obj.elevator.elevator_name

    def get_workers(self, obj):
        worker = obj.worker
        worker = json.loads(worker)
        worker_1 = Person.objects.get(id=worker[0])
        worker_2 = Person.objects.get(id=worker[1])
        return [
            {"worker_1": worker_1.id, "name": worker_1.auth_user.real_name},
            {"worker_2": worker_2.id, "name": worker_2.auth_user.real_name}
            ]

    def get_workers_all(self, obj):
        worker = obj.worker
        worker = json.loads(worker)
        l = len(worker)
        w = []
        for i in range(l):
            try:
                person_id = worker[i]
                p = Person.objects.get(id=person_id)
                k = "worker_" + str(i + 1)
                w.append({k: person_id, "name": p.auth_user.real_name})
            except Exception as e:
                print e
                print u"维保人员被删除"
        return w

    def get_t_lng(self, obj):
        return float(obj.lng) if obj.lng else 0.00

    def get_t_lat(self, obj):
        return float(obj.lat) if obj.lat else 0.00

    def get_register_code(self, obj):
        return obj.elevator.register_code

    def get_use_company(self, obj):
        return obj.elevator.property_company.name


class AppTaskStatusSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ("id", "status", "estate_confirm", "result", "signature", "maintain_signature", "maintainer_name",
                  "property_comfirm_time", "maintainer_id", "task_start_time")


class AppTaskSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ("id", "status", "result", "task_end_time", "lng", "lat", "task_start_time")


class MaintainHistoryListSerializer(serializers.ModelSerializer):
    last_time = serializers.SerializerMethodField()
    # next_time = serializers.SerializerMethodField()
    # status = serializers.SerializerMethodField()
    first_maintain_time = serializers.SerializerMethodField()

    class Meta:
        model = ElevatorInfo
        fields = ('id', "register_code", "maintain_company_name", "property_company_name", "last_time",
                  "first_maintain_time")

    def get_last_time(self, obj):
        elevator_id = obj.id
        task_obj = Task.objects.filter_active(elevator=elevator_id).exclude(task_end_time=None).last()
        if task_obj:
            last_time = task_obj.task_end_time
            last_time = str(last_time).split(' ')[0]
            return last_time
        else:
            return None

    def get_first_maintain_time(self, obj):
        elevator_id = obj.id
        task_obj = Task.objects.filter_active(elevator=obj).first()
        first_maintain_time = task_obj.day
        return first_maintain_time


class MaintainHistoryDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = ElevatorInfo
        fields = ('id', "register_code", "maintain_company_name", "property_company_name", "elevator_name",
                  "elevator_no", "elevator_model")


class TaskHistoryListSerializer(serializers.ModelSerializer):
    status = serializers.SerializerMethodField()
    maintain_person = serializers.SerializerMethodField()
    task_end_time = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = ('id', 'sn', 'day', 'task_end_time', 'status', 'maintain_person')

    def get_status(self, obj):
        now_time = datetime.datetime.now().strftime("%Y-%m-%d")
        if obj.status == 10:
            if now_time <= str(obj.day):
                status = u'未开始'
            else:
                status = u'已超期'
            return status
        # elif obj.status == 20:
        #     status = u'进行中'
        #     return status
        # elif obj.status == 30:
        #     status = u'完成(未确认)'
        #     return status
        # elif obj.status == 40:
        #     status = u'完成(已确认)'
        #     return status
        # elif obj.status == 50:
        #     status = u'转移中'
        #     return status
        return obj.get_status_display()

    def get_maintain_person(self, obj):
        if obj.status in [10, 50]:
            maintain_person = None
            return maintain_person
        else:
            person_id = obj.update_by
            person_obj = AuthUser.objects.get(id=person_id)
            if person_obj:
                maintain_person = person_obj.real_name
                return maintain_person
            else:
                maintain_person = None
                return maintain_person

    def get_task_end_time(self, obj):
        if obj.task_end_time:
            task_end_time = str(obj.task_end_time).split(' ')[0]
            return task_end_time
        else:
            return None


class DataStorageSerializer(serializers.ModelSerializer):

    class Meta:
        model = DataStorage
        fields = ("update_by", "service_id", "result", "task", "position")


class TaskResultSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ("id", "result", "estate_confirm", "property_comfirm_time", "signature", "task_end_time")


























